<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>ShardingSphere-XA事务无法恢复问题定位 | flyingzc's blog</title><meta name="author" content="flyingzc"><meta name="copyright" content="flyingzc"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="ShardingSphere-XA事务无法恢复问题定位问题背景在测试 ShardingSphere-Proxy 使用达梦数据库开启 XA 事务进行压测期间，kill 掉达梦数据库，等一段时间再重启达梦数据库，最终未完成的 XA 事务无法恢复，数据产生不一致。查看达梦上的 xid 一直有残留，没有被处理。使用 ShardingSphere-Proxy 结合其他主流数据库进行测试时无该问题。 通过日志">
<meta property="og:type" content="article">
<meta property="og:title" content="ShardingSphere-XA事务无法恢复问题定位">
<meta property="og:url" content="https://flyingzc.github.io/articles/shardingsphere/ShardingSphere-XA%E4%BA%8B%E5%8A%A1%E6%97%A0%E6%B3%95%E6%81%A2%E5%A4%8D%E9%97%AE%E9%A2%98.html">
<meta property="og:site_name" content="flyingzc&#39;s blog">
<meta property="og:description" content="ShardingSphere-XA事务无法恢复问题定位问题背景在测试 ShardingSphere-Proxy 使用达梦数据库开启 XA 事务进行压测期间，kill 掉达梦数据库，等一段时间再重启达梦数据库，最终未完成的 XA 事务无法恢复，数据产生不一致。查看达梦上的 xid 一直有残留，没有被处理。使用 ShardingSphere-Proxy 结合其他主流数据库进行测试时无该问题。 通过日志">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://flyingzc.github.io/images/zc-icon.jpeg">
<meta property="article:published_time" content="2024-02-27T16:00:00.000Z">
<meta property="article:modified_time" content="2025-01-21T01:51:41.214Z">
<meta property="article:author" content="flyingzc">
<meta property="article:tag" content="Transaction">
<meta property="article:tag" content="Narayana">
<meta property="article:tag" content="ShardingSphere">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://flyingzc.github.io/images/zc-icon.jpeg"><script type="application/ld+json">{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "ShardingSphere-XA事务无法恢复问题定位",
  "url": "https://flyingzc.github.io/articles/shardingsphere/ShardingSphere-XA%E4%BA%8B%E5%8A%A1%E6%97%A0%E6%B3%95%E6%81%A2%E5%A4%8D%E9%97%AE%E9%A2%98.html",
  "image": "https://flyingzc.github.io/images/zc-icon.jpeg",
  "datePublished": "2024-02-27T16:00:00.000Z",
  "dateModified": "2025-01-21T01:51:41.214Z",
  "author": [
    {
      "@type": "Person",
      "name": "flyingzc",
      "url": "https://flyingzc.github.io/"
    }
  ]
}</script><link rel="shortcut icon" href="/images/zc-icon.jpeg"><link rel="canonical" href="https://flyingzc.github.io/articles/shardingsphere/ShardingSphere-XA%E4%BA%8B%E5%8A%A1%E6%97%A0%E6%B3%95%E6%81%A2%E5%A4%8D%E9%97%AE%E9%A2%98.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="google-site-verification" content="DentpX3LnP_WNgEeFnNIcTZZky-Bby-zL-uI_9GqTAw"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><script>
    (() => {
      
    const saveToLocal = {
      set: (key, value, ttl) => {
        if (!ttl) return
        const expiry = Date.now() + ttl * 86400000
        localStorage.setItem(key, JSON.stringify({ value, expiry }))
      },
      get: key => {
        const itemStr = localStorage.getItem(key)
        if (!itemStr) return undefined
        const { value, expiry } = JSON.parse(itemStr)
        if (Date.now() > expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return value
      }
    }

    window.btf = {
      saveToLocal,
      getScript: (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        Object.entries(attr).forEach(([key, val]) => script.setAttribute(key, val))
        script.onload = script.onreadystatechange = () => {
          if (!script.readyState || /loaded|complete/.test(script.readyState)) resolve()
        }
        script.onerror = reject
        document.head.appendChild(script)
      }),
      getCSS: (url, id) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onload = link.onreadystatechange = () => {
          if (!link.readyState || /loaded|complete/.test(link.readyState)) resolve()
        }
        link.onerror = reject
        document.head.appendChild(link)
      }),
      addGlobalFn: (key, fn, name = false, parent = window) => {
        if (!false && key.startsWith('pjax')) return
        const globalFn = parent.globalFn || {}
        globalFn[key] = globalFn[key] || {}
        globalFn[key][name || Object.keys(globalFn[key]).length] = fn
        parent.globalFn = globalFn
      }
    }
  
      
      const activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      const activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }

      btf.activateDarkMode = activateDarkMode
      btf.activateLightMode = activateLightMode

      const theme = saveToLocal.get('theme')
    
          theme === 'dark' ? activateDarkMode() : theme === 'light' ? activateLightMode() : null
        
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        document.documentElement.classList.toggle('hide-aside', asideStatus === 'hide')
      }
    
      
    const detectApple = () => {
      if (/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)) {
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
  
    })()
  </script><script async="async" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><script>(adsbygoogle = window.adsbygoogle || []).push({
  google_ad_client: '',
  enable_page_level_ads: 'true'
});</script><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false,"highlightFullpage":false,"highlightMacStyle":false},
  copy: {
    success: '复制成功',
    error: '复制失败',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'null',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyloadPlugin: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'ShardingSphere-XA事务无法恢复问题定位',
  isHighlightShrink: false,
  isToc: true,
  pageType: 'post'
}</script><link rel="stylesheet" href="/self/github-dark.css"><meta name="generator" content="Hexo 7.0.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img text-center"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data text-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog-info"><a class="nav-site-title" href="/"><span class="site-name">flyingzc's blog</span></a><a class="nav-page-title" href="/"><span class="site-name">ShardingSphere-XA事务无法恢复问题定位</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><span class="site-page"><i class="fas fa-bars fa-fw"></i></span></div></div></nav><div id="post-info"><h1 class="post-title">ShardingSphere-XA事务无法恢复问题定位</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2024-02-27T16:00:00.000Z" title="发表于 2024-02-28 00:00:00">2024-02-28</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2025-01-21T01:51:41.214Z" title="更新于 2025-01-21 09:51:41">2025-01-21</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Transaction/">Transaction</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title=""><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">浏览量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="container post-content" id="article-container"><h1 id="ShardingSphere-XA事务无法恢复问题定位"><a href="#ShardingSphere-XA事务无法恢复问题定位" class="headerlink" title="ShardingSphere-XA事务无法恢复问题定位"></a>ShardingSphere-XA事务无法恢复问题定位</h1><h2 id="问题背景"><a href="#问题背景" class="headerlink" title="问题背景"></a>问题背景</h2><p>在测试 ShardingSphere-Proxy 使用达梦数据库开启 XA 事务进行压测期间，kill 掉达梦数据库，等一段时间再重启达梦数据库，最终未完成的 XA 事务无法恢复，数据产生不一致。<br>查看达梦上的 xid 一直有残留，没有被处理。<br>使用 ShardingSphere-Proxy 结合其他主流数据库进行测试时无该问题。</p>
<p>通过日志可以看到在压测期间，挂掉达梦数据库之后，有大量连接报错。节选错误日志如下：<br>比如下面这段日志，在执行 xa end 操作时，因为达梦数据库连接不上，达梦驱动报错如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><code class="hljs log">[WARN ] 2024-01-29 11:11:19.867 [Connection-82-ThreadExecutor] com.arjuna.ats.jta - ARJUNA016041: prepare on &lt; formatId=131077, gtrid_length=64, bqual_length=36, tx_uid=0:ffff7f000001:926b:65b7167e:5a4e, node_name=806e4bdb-b629-434b-bcee-0d86fa9cb8b0, branch_uid=0:ffff7f000001:926b:65b7167e:5a54, subordinatenodename=null, eis_name=0 &gt; (org.apache.shardingsphere.transaction.xa.spi.SingleXAResource@169b2776) failed with exception ARJUNA016099: Unknown error code:6001<br>dm.jdbc.driver.DmdbXAException: Communication  error<br>	at dm.jdbc.driver.DBError.throwXAException(DBError.java:795)<br>	at dm.jdbc.a.a.a(DBAccess.java:1315)<br>	at dm.jdbc.driver.DmdbXAResource.end(DmdbXAResource.java:104)<br>	at org.apache.shardingsphere.transaction.xa.spi.SingleXAResource.end(SingleXAResource.java:51)<br>	at com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple.doEnd(TransactionImple.java:1087)<br>	at com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple.endAssociation(TransactionImple.java:1058)<br>	at com.arjuna.ats.internal.jta.resources.arjunacore.XAResourceRecord.endAssociation(XAResourceRecord.java:1295)<br>	at com.arjuna.ats.internal.jta.resources.arjunacore.XAResourceRecord.topLevelPrepare(XAResourceRecord.java:210)<br>	at com.arjuna.ats.arjuna.coordinator.BasicAction.doPrepare(BasicAction.java:2678)<br>	at com.arjuna.ats.arjuna.coordinator.BasicAction.doPrepare(BasicAction.java:2628)<br>	at com.arjuna.ats.arjuna.coordinator.BasicAction.prepare(BasicAction.java:2162)<br>	at com.arjuna.ats.arjuna.coordinator.BasicAction.End(BasicAction.java:1508)<br>	at com.arjuna.ats.arjuna.coordinator.TwoPhaseCoordinator.end(TwoPhaseCoordinator.java:96)<br>	at com.arjuna.ats.arjuna.AtomicAction.commit(AtomicAction.java:162)<br>	at com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple.commitAndDisassociate(TransactionImple.java:1295)<br>	at com.arjuna.ats.internal.jta.transaction.arjunacore.BaseTransaction.commit(BaseTransaction.java:128)<br>	at org.apache.shardingsphere.transaction.xa.XAShardingSphereTransactionManager.commit(XAShardingSphereTransactionManager.java:129)<br>	at org.apache.shardingsphere.proxy.backend.connector.jdbc.transaction.BackendTransactionManager.commit(BackendTransactionManager.java:94)<br>	at org.apache.shardingsphere.proxy.backend.connector.DatabaseConnector.doExecuteWithImplicitCommitTransaction(DatabaseConnector.java:259)<br>	at org.apache.shardingsphere.proxy.backend.connector.DatabaseConnector.execute(DatabaseConnector.java:228)<br>	at org.apache.shardingsphere.proxy.frontend.mysql.command.query.text.query.MySQLComQueryPacketExecutor.execute(MySQLComQueryPacketExecutor.java:99)<br>	at org.apache.shardingsphere.proxy.frontend.command.CommandExecutorTask.doExecuteCommand(CommandExecutorTask.java:129)<br>	at org.apache.shardingsphere.proxy.frontend.command.CommandExecutorTask.executeCommand(CommandExecutorTask.java:124)<br>	at org.apache.shardingsphere.proxy.frontend.command.CommandExecutorTask.run(CommandExecutorTask.java:78)<br>	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)<br>	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)<br>	at java.lang.Thread.run(Thread.java:748)<br></code></pre></td></tr></table></figure>

<p>下面这段日志，在执行 xa prepare 操作时，因为数据库连接不上，达梦驱动报错如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><code class="hljs log">[WARN ] 2024-01-29 11:11:19.860 [Connection-85-ThreadExecutor] com.arjuna.ats.jta - ARJUNA016041: prepare on &lt; formatId=131077, gtrid_length=64, bqual_length=36, tx_uid=0:ffff7f000001:926b:65b7167e:5af8, node_name=806e4bdb-b629-434b-bcee-0d86fa9cb8b0, branch_uid=0:ffff7f000001:926b:65b7167e:5b14, subordinatenodename=null, eis_name=0 &gt; (org.apache.shardingsphere.transaction.xa.spi.SingleXAResource@4ce53a0a) failed with exception ARJUNA016099: Unknown error code:6001<br>dm.jdbc.driver.DmdbXAException: Communication  error<br>	at dm.jdbc.driver.DBError.throwXAException(DBError.java:795)<br>	at dm.jdbc.a.a.a(DBAccess.java:1315)<br>	at dm.jdbc.driver.DmdbXAResource.prepare(DmdbXAResource.java:174)<br>	at org.apache.shardingsphere.transaction.xa.spi.SingleXAResource.prepare(SingleXAResource.java:73)<br>	at com.arjuna.ats.internal.jta.resources.arjunacore.XAResourceRecord.topLevelPrepare(XAResourceRecord.java:214)<br>	at com.arjuna.ats.arjuna.coordinator.BasicAction.doPrepare(BasicAction.java:2678)<br>	at com.arjuna.ats.arjuna.coordinator.BasicAction.doPrepare(BasicAction.java:2628)<br>	at com.arjuna.ats.arjuna.coordinator.BasicAction.prepare(BasicAction.java:2162)<br>	at com.arjuna.ats.arjuna.coordinator.BasicAction.End(BasicAction.java:1508)<br>	at com.arjuna.ats.arjuna.coordinator.TwoPhaseCoordinator.end(TwoPhaseCoordinator.java:96)<br>	at com.arjuna.ats.arjuna.AtomicAction.commit(AtomicAction.java:162)<br>	at com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple.commitAndDisassociate(TransactionImple.java:1295)<br>	at com.arjuna.ats.internal.jta.transaction.arjunacore.BaseTransaction.commit(BaseTransaction.java:128)<br>	at org.apache.shardingsphere.transaction.xa.XAShardingSphereTransactionManager.commit(XAShardingSphereTransactionManager.java:129)<br>	at org.apache.shardingsphere.proxy.backend.connector.jdbc.transaction.BackendTransactionManager.commit(BackendTransactionManager.java:94)<br>	at org.apache.shardingsphere.proxy.backend.connector.DatabaseConnector.doExecuteWithImplicitCommitTransaction(DatabaseConnector.java:259)<br>	at org.apache.shardingsphere.proxy.backend.connector.DatabaseConnector.execute(DatabaseConnector.java:228)<br>	at org.apache.shardingsphere.proxy.frontend.mysql.command.query.text.query.MySQLComQueryPacketExecutor.execute(MySQLComQueryPacketExecutor.java:99)<br>	at org.apache.shardingsphere.proxy.frontend.command.CommandExecutorTask.doExecuteCommand(CommandExecutorTask.java:129)<br>	at org.apache.shardingsphere.proxy.frontend.command.CommandExecutorTask.executeCommand(CommandExecutorTask.java:124)<br>	at org.apache.shardingsphere.proxy.frontend.command.CommandExecutorTask.run(CommandExecutorTask.java:78)<br>	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)<br>	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)<br>	at java.lang.Thread.run(Thread.java:748)<br></code></pre></td></tr></table></figure>

<p>xa commit 阶段，因为数据库连接不上，达梦驱动报错如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><code class="hljs log">[WARN ] 2024-01-29 11:11:19.865 [Connection-56-ThreadExecutor] com.arjuna.ats.jta - ARJUNA016036: commit on &lt; formatId=131077, gtrid_length=64, bqual_length=36, tx_uid=0:ffff7f000001:926b:65b7167e:58be, node_name=806e4bdb-b629-434b-bcee-0d86fa9cb8b0, branch_uid=0:ffff7f000001:926b:65b7167e:58c8, subordinatenodename=null, eis_name=0 &gt; (org.apache.shardingsphere.transaction.xa.spi.SingleXAResource@576dcbef) failed with exception $ARJUNA016099: Unknown error code:6001<br>dm.jdbc.driver.DmdbXAException: Communication  error<br>	at dm.jdbc.driver.DBError.throwXAException(DBError.java:795)<br>	at dm.jdbc.a.a.a(DBAccess.java:1315)<br>	at dm.jdbc.driver.DmdbXAResource.commit(DmdbXAResource.java:88)<br>	at org.apache.shardingsphere.transaction.xa.spi.SingleXAResource.commit(SingleXAResource.java:44)<br>	at com.arjuna.ats.internal.jta.resources.arjunacore.XAResourceRecord.topLevelCommit(XAResourceRecord.java:473)<br>	at com.arjuna.ats.arjuna.coordinator.BasicAction.doCommit(BasicAction.java:2906)<br>	at com.arjuna.ats.arjuna.coordinator.BasicAction.doCommit(BasicAction.java:2822)<br>	at com.arjuna.ats.arjuna.coordinator.BasicAction.phase2Commit(BasicAction.java:1878)<br>	at com.arjuna.ats.arjuna.coordinator.BasicAction.End(BasicAction.java:1534)<br>	at com.arjuna.ats.arjuna.coordinator.TwoPhaseCoordinator.end(TwoPhaseCoordinator.java:96)<br>	at com.arjuna.ats.arjuna.AtomicAction.commit(AtomicAction.java:162)<br>	at com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple.commitAndDisassociate(TransactionImple.java:1295)<br>	at com.arjuna.ats.internal.jta.transaction.arjunacore.BaseTransaction.commit(BaseTransaction.java:128)<br>	at org.apache.shardingsphere.transaction.xa.XAShardingSphereTransactionManager.commit(XAShardingSphereTransactionManager.java:129)<br>	at org.apache.shardingsphere.proxy.backend.connector.jdbc.transaction.BackendTransactionManager.commit(BackendTransactionManager.java:94)<br>	at org.apache.shardingsphere.proxy.backend.connector.DatabaseConnector.doExecuteWithImplicitCommitTransaction(DatabaseConnector.java:259)<br>	at org.apache.shardingsphere.proxy.backend.connector.DatabaseConnector.execute(DatabaseConnector.java:228)<br>	at org.apache.shardingsphere.proxy.frontend.mysql.command.query.text.query.MySQLComQueryPacketExecutor.execute(MySQLComQueryPacketExecutor.java:99)<br>	at org.apache.shardingsphere.proxy.frontend.command.CommandExecutorTask.doExecuteCommand(CommandExecutorTask.java:129)<br>	at org.apache.shardingsphere.proxy.frontend.command.CommandExecutorTask.executeCommand(CommandExecutorTask.java:124)<br>	at org.apache.shardingsphere.proxy.frontend.command.CommandExecutorTask.run(CommandExecutorTask.java:78)<br>	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)<br>	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)<br>	at java.lang.Thread.run(Thread.java:748)<br></code></pre></td></tr></table></figure>

<p>持续观察日志，能够看到 xa recover 查询出来的 xid 在不断增多。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs log">[INFO ] 2024-01-29 11:11:53.159 [Periodic Recovery] o.a.s.t.x.n.m.DataSourceXAResourceRecoveryHelper - 115174042, recover, result:[dm.jdbc.driver.DmdbXid@6466d28f, dm.jdbc.driver.DmdbXid@2179218b, dm.jdbc.driver.DmdbXid@7cd785b1, dm.jdbc.driver.DmdbXid@2f889463, dm.jdbc.driver.DmdbXid@7da8d9b7, dm.jdbc.driver.DmdbXid@1535daf0, dm.jdbc.driver.DmdbXid@550f3fea, dm.jdbc.driver.DmdbXid@3ecf92a4, dm.jdbc.driver.DmdbXid@59181ab, dm.jdbc.driver.DmdbXid@3e4829b3, dm.jdbc.driver.DmdbXid@1294a1ff, dm.jdbc.driver.DmdbXid@500c5bbb, dm.jdbc.driver.DmdbXid@599914c8, dm.jdbc.driver.DmdbXid@2663abf9, dm.jdbc.driver.DmdbXid@11cf7d93, dm.jdbc.driver.DmdbXid@232c3d92, dm.jdbc.driver.DmdbXid@3282426b, dm.jdbc.driver.DmdbXid@9051ba1, dm.jdbc.driver.DmdbXid@63ccccf7, dm.jdbc.driver.DmdbXid@21ceadb1, dm.jdbc.driver.DmdbXid@17f32f9, dm.jdbc.driver.DmdbXid@2006e964, dm.jdbc.driver.DmdbXid@25a832e7, dm.jdbc.driver.DmdbXid@71dfb0c6, dm.jdbc.driver.DmdbXid@94fbcfe, dm.jdbc.driver.DmdbXid@1e15297a, dm.jdbc.driver.DmdbXid@7a4e0f55, dm.jdbc.driver.DmdbXid@761bc95a, dm.jdbc.driver.DmdbXid@247332b, dm.jdbc.driver.DmdbXid@352e94e0, dm.jdbc.driver.DmdbXid@3f9001b7, dm.jdbc.driver.DmdbXid@17e95e06, dm.jdbc.driver.DmdbXid@2c0cf9bb, dm.jdbc.driver.DmdbXid@6dc4f14e, dm.jdbc.driver.DmdbXid@5266c8f8, dm.jdbc.driver.DmdbXid@fa2a5dc, dm.jdbc.driver.DmdbXid@44a844b2, dm.jdbc.driver.DmdbXid@e2c93e8, dm.jdbc.driver.DmdbXid@6ae9bbdd, dm.jdbc.driver.DmdbXid@707f6f19, dm.jdbc.driver.DmdbXid@76742870, dm.jdbc.driver.DmdbXid@1cad4685, dm.jdbc.driver.DmdbXid@3b3d219e, dm.jdbc.driver.DmdbXid@30319647, dm.jdbc.driver.DmdbXid@67d11f99, dm.jdbc.driver.DmdbXid@113ee488, dm.jdbc.driver.DmdbXid@435d06e0, dm.jdbc.driver.DmdbXid@7fe22362, dm.jdbc.driver.DmdbXid@1020d6d0, dm.jdbc.driver.DmdbXid@76dc7af8, dm.jdbc.driver.DmdbXid@5d1d18c5, dm.jdbc.driver.DmdbXid@338ac937, dm.jdbc.driver.DmdbXid@258a1fc0, dm.jdbc.driver.DmdbXid@3014aa33, dm.jdbc.driver.DmdbXid@5fa57c4, dm.jdbc.driver.DmdbXid@60dcf53d, dm.jdbc.driver.DmdbXid@15dd92f9, dm.jdbc.driver.DmdbXid@8de743, dm.jdbc.driver.DmdbXid@579ed4e1, dm.jdbc.driver.DmdbXid@506cb632, dm.jdbc.driver.DmdbXid@29dfbc9c, dm.jdbc.driver.DmdbXid@4607f11b, dm.jdbc.driver.DmdbXid@679f1ce6, dm.jdbc.driver.DmdbXid@52f7fb01], delegate:class dm.jdbc.driver.DmdbXAResource<br></code></pre></td></tr></table></figure>

<p>日志中没有看到期望的二阶段恢复操作，可疑的异常日志如下：<code>Transaction 0:ffff7f000001:926b:65b7167e:5a65 restored heuristic participant</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs log">2024-01-29 14:09:25.984 [Periodic Recovery] WARN  com.arjuna.ats.jta - ARJUNA016037: Could not find new XAResource to use for recovering non-serializable XAResource XAResourceRecord &lt; resource:null, txid:&lt; formatId=131077, gtrid_length=64, bqual_length=36, tx_uid=0:ffff7f000001:926b:65b7167e:5a65, node_name=806e4bdb-b629-434b-bcee-0d86fa9cb8b0, branch_uid=0:ffff7f000001:926b:65b7167e:5a76, subordinatenodename=null, eis_name=0 &gt;, heuristic: TwoPhaseOutcome.HEURISTIC_HAZARD com.arjuna.ats.internal.jta.resources.arjunacore.XAResourceRecord@6c769e03 &gt;<br>2024-01-29 14:09:25.984 [Periodic Recovery] WARN  com.arjuna.ats.jta - XAResourceRecord restored heuristic instance: XAResourceRecord &lt; resource:null, txid:&lt; formatId=131077, gtrid_length=64, bqual_length=36, tx_uid=0:ffff7f000001:926b:65b7167e:5a65, node_name=806e4bdb-b629-434b-bcee-0d86fa9cb8b0, branch_uid=0:ffff7f000001:926b:65b7167e:5a76, subordinatenodename=null, eis_name=0 &gt;, heuristic: TwoPhaseOutcome.HEURISTIC_HAZARD com.arjuna.ats.internal.jta.resources.arjunacore.XAResourceRecord@6c769e03 &gt;<br>2024-01-29 14:09:25.985 [Periodic Recovery] TRACE com.arjuna.ats.arjuna - RecordList::insert(RecordList: empty) : appending /StateManager/AbstractRecord/XAResourceRecord for 0:ffff7f000001:926b:65b7167e:5a77<br>2024-01-29 14:09:25.985 [Periodic Recovery] WARN  com.arjuna.ats.arjuna - Transaction 0:ffff7f000001:926b:65b7167e:5a65 restored heuristic participant XAResourceRecord &lt; resource:null, txid:&lt; formatId=131077, gtrid_length=64, bqual_length=36, tx_uid=0:ffff7f000001:926b:65b7167e:5a65, node_name=806e4bdb-b629-434b-bcee-0d86fa9cb8b0, branch_uid=0:ffff7f000001:926b:65b7167e:5a76, subordinatenodename=null, eis_name=0 &gt;, heuristic: TwoPhaseOutcome.HEURISTIC_HAZARD com.arjuna.ats.internal.jta.resources.arjunacore.XAResourceRecord@6c769e03 &gt;<br>2024-01-29 14:09:25.985 [Periodic Recovery] TRACE com.arjuna.ats.arjuna - HeuristicList - Unpacked a 463 record<br></code></pre></td></tr></table></figure>

<p>所以现在的问题就是 ShardingSphere-Proxy 能够查询出来 dameng 上没完成的事务，但是没有执行二阶段 xa commit 或 xa rollback 操作，具体原因需要继续分析。</p>
<p>同样对比 Oracle 数据库，在 XA 事务压测期间 kill 掉 Oracle，后续再重启 Oracle 事务是可以正常恢复的，最终数据一致。日志如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs log">[INFO ] 2024-01-29 11:04:29.279 [Periodic Recovery] o.a.s.t.x.n.m.DataSourceXAResourceRecoveryHelper - 497281350, recover, result:[oracle.jdbc.xa.OracleXid@20b27], delegate:class oracle.jdbc.driver.T4CXAResource<br><br>[INFO ] 2024-01-29 11:04:30.285 [Periodic Recovery] o.a.s.t.x.n.m.DataSourceXAResourceRecoveryHelper - 497281350, rollback, xid:&lt; formatId=131077, gtrid_length=64, bqual_length=36, tx_uid=0:ffff7f000001:a7f4:65b7143a:351b, node_name=15774b67-7ca7-4b1b-90ee-e18fec83225b, branch_uid=0:ffff7f000001:a7f4:65b7143a:351c, subordinatenodename=null, eis_name=0 &gt;<br></code></pre></td></tr></table></figure>

<h2 id="问题定位"><a href="#问题定位" class="headerlink" title="问题定位"></a>问题定位</h2><h3 id="本地搭建环境尝试复现问题"><a href="#本地搭建环境尝试复现问题" class="headerlink" title="本地搭建环境尝试复现问题"></a>本地搭建环境尝试复现问题</h3><p>前置准备:<br>1.执行脚本清理 dameng 和 mysql 数据库上残留的 xid 和锁，清理数据。<br>2.proxy 配置。</p>
<p>本地在 ShardingSphere-Proxy 执行 xa commit 之前，调用 shell 自动 kill 掉数据库，模拟二阶段 commit 失败，后续查看事务恢复流程。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">SingleXAResource</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">XAResource</span> &#123;<br><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> String resourceName;<br><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> XAResource delegate;<br><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-type">AtomicBoolean</span> <span class="hljs-variable">killed</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">AtomicBoolean</span>();<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">commit</span><span class="hljs-params">(<span class="hljs-keyword">final</span> Xid xid, <span class="hljs-keyword">final</span> <span class="hljs-type">boolean</span> onePhase)</span> <span class="hljs-keyword">throws</span> XAException &#123;<br>        count.getAndIncrement();<br>        <span class="hljs-comment">// 在执行 xa commit 之前自动 kill 掉数据库实例</span><br>        <span class="hljs-keyword">if</span> (killed.compareAndSet(<span class="hljs-literal">false</span>, <span class="hljs-literal">true</span>)) &#123;<br>            ShellUtil.callShellByExec(<span class="hljs-string">&quot;docker stop mysqlv8-14310&quot;</span>);<br>        &#125;<br>        delegate.commit(xid, onePhase);<br>    &#125;<br>    <span class="hljs-comment">// ...</span><br>&#125;<br></code></pre></td></tr></table></figure>

<p>后续本地 debug 一直发现达梦数据库挂掉和 mysql 数据库挂掉后，两个后续执行的逻辑不一样。</p>
<p>mysql 的话，会正常走恢复流程。而达梦残留的 xa 事务一直被忽略处理。</p>
<p>最后 debug mysql 挂掉 和 达梦挂掉之后的区别。</p>
<p><code>发现二者在调用 xa 接口时因为数据库挂掉返回的错误码不一致，达梦返回的错误码没有按照 xa 规范进行处理，所以事务管理器 TM 无法根据错误码执行后续恢复操作。</code></p>
<h3 id="MySQL-挂掉后事务恢复流程"><a href="#MySQL-挂掉后事务恢复流程" class="headerlink" title="MySQL 挂掉后事务恢复流程"></a>MySQL 挂掉后事务恢复流程</h3><p>MySQL JDBC 驱动处理逻辑如下:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// com.mysql.cj.jdbc.MysqlXAConnection</span><br><span class="hljs-comment">// MySQL 驱动会对数据库异常处理成符合 XA 规范的错误码返回。</span><br><span class="hljs-keyword">protected</span> <span class="hljs-keyword">static</span> XAException <span class="hljs-title function_">mapXAExceptionFromSQLException</span><span class="hljs-params">(SQLException sqlEx)</span> &#123;<br>    <span class="hljs-type">Integer</span> <span class="hljs-variable">xaCode</span> <span class="hljs-operator">=</span> (Integer)MYSQL_ERROR_CODES_TO_XA_ERROR_CODES.get(sqlEx.getErrorCode());<br>    <span class="hljs-keyword">return</span> xaCode != <span class="hljs-literal">null</span> ? (XAException)(<span class="hljs-keyword">new</span> <span class="hljs-title class_">MysqlXAException</span>(xaCode, sqlEx.getMessage(), (String)<span class="hljs-literal">null</span>)).initCause(sqlEx) : (XAException)(<span class="hljs-keyword">new</span> <span class="hljs-title class_">MysqlXAException</span>(-<span class="hljs-number">7</span>, Messages.getString(<span class="hljs-string">&quot;MysqlXAConnection.003&quot;</span>), (String)<span class="hljs-literal">null</span>)).initCause(sqlEx);<br>&#125;<br></code></pre></td></tr></table></figure>

<p>MySQL 在执行 xa commit 等阶段因为数据库挂掉报错如下，返回错误码 -7<br><img src="/images/img-20240130092247.png"></p>
<p>查看 JTA 规范里 XAException 类中定义的错误码，-7 表示 RM unavailable.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs Java"><span class="hljs-comment">// javax.transaction.xa.XAException</span><br><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * Resource manager is unavailable.</span><br><span class="hljs-comment"> */</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">static</span> <span class="hljs-type">int</span> <span class="hljs-variable">XAER_RMFAIL</span> <span class="hljs-operator">=</span> -<span class="hljs-number">7</span>;<br></code></pre></td></tr></table></figure>

<p><img src="/images/img-20240130092437.png"><br>Narayana 正确处理该错误码，后续进行事务恢复操作。</p>
<h3 id="达梦挂掉后事务恢复流程"><a href="#达梦挂掉后事务恢复流程" class="headerlink" title="达梦挂掉后事务恢复流程"></a>达梦挂掉后事务恢复流程</h3><p><img src="/images/img-20240129170112.png"></p>
<p>返回错误码 6001，看起来像是一个内部错误码，没有按照 XA 规范返回正确的错误码。会走最后一个分支，后续该事务无法恢复。<br><img src="/images/img-20240129170053.png"></p>
<p>HEURISTIC_HAZARD 的含义如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 在准备阶段之后，一些子参与者已经提交，一些已经回滚，还有一些我们不清楚。</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">int</span> <span class="hljs-variable">HEURISTIC_HAZARD</span> <span class="hljs-operator">=</span> <span class="hljs-number">6</span>;  <span class="hljs-comment">// after prepare some sub-participants committed, some rolled back and some we don&#x27;t know</span><br></code></pre></td></tr></table></figure>

<h3 id="XA规范"><a href="#XA规范" class="headerlink" title="XA规范"></a>XA规范</h3><p>XA 规范中明确定义了 xa_commit 等操作应该返回的错误码。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">-- 第47页<br>XAException.XAER_RMFAIL is used when some connection error happens and it is expected that reconnection of RM could occur<br><br>当发生某些连接错误时使用 XAException.XAER_RMFAIL，预计 RM 可能会重新连接<br></code></pre></td></tr></table></figure>
<p><img src="/images/img-20240228191411.png"></p>
<h3 id="其他数据库处理流程"><a href="#其他数据库处理流程" class="headerlink" title="其他数据库处理流程"></a>其他数据库处理流程</h3><h4 id="postgresql-驱动处理-xa-异常逻辑"><a href="#postgresql-驱动处理-xa-异常逻辑" class="headerlink" title="postgresql 驱动处理 xa 异常逻辑"></a>postgresql 驱动处理 xa 异常逻辑</h4><p>Pg 同样处理，当数据库连接异常时返回 <em><strong>XAER_RMFAIL</strong></em> 错误码<br><img src="/images/img-20240130092621.png"></p>
<h2 id="问题解决"><a href="#问题解决" class="headerlink" title="问题解决"></a>问题解决</h2><p>在TM侧兼容达梦原生异常，或者RM驱动修复返回正确的错误码即可。</p>
<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><p><a target="_blank" rel="noopener" href="https://jbossts.blogspot.com/2019/09/heuristic-exceptions.html">narayana Heuristic异常</a></p>
<p><a target="_blank" rel="noopener" href="https://pubs.opengroup.org/onlinepubs/009680699/toc.pdf">xa规范文档</a></p>
<p><a target="_blank" rel="noopener" href="https://github.com/pgjdbc/pgjdbc/pull/782">pg驱动对xa-commit异常处理的代码</a></p>
<link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10/dist/style.css"><script src="https://fastly.jsdelivr.net/npm/d3@7"></script><script src="https://fastly.jsdelivr.net/npm/markmap-view@0.18.10"></script><script src="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10"></script>
<link rel="stylesheet" href="/css/markmap.css">

<script src="/js/markmap.js"></script>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io">flyingzc</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io/articles/shardingsphere/ShardingSphere-XA%E4%BA%8B%E5%8A%A1%E6%97%A0%E6%B3%95%E6%81%A2%E5%A4%8D%E9%97%AE%E9%A2%98.html">https://flyingzc.github.io/articles/shardingsphere/ShardingSphere-XA%E4%BA%8B%E5%8A%A1%E6%97%A0%E6%B3%95%E6%81%A2%E5%A4%8D%E9%97%AE%E9%A2%98.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来源 <a href="https://flyingzc.github.io" target="_blank">flyingzc's blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Transaction/">Transaction</a><a class="post-meta__tags" href="/tags/Narayana/">Narayana</a><a class="post-meta__tags" href="/tags/ShardingSphere/">ShardingSphere</a></div><div class="post-share"><div class="social-share" data-image="/images/zc-icon.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><a class="pagination-related" href="/articles/shardingsphere/ShardingSphere-Narayana-XA%E4%BA%8B%E5%8A%A1%E4%B8%8D%E5%9B%9E%E6%BB%9A%E9%97%AE%E9%A2%98%E5%AE%9A%E4%BD%8D.html" title="ShardingSphere Narayana XA 事务不回滚问题定位"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2024-02-29</div><div class="info-item-2">ShardingSphere Narayana XA 事务不回滚问题定位</div></div><div class="info-2"><div class="info-item-1">ShardingSphere Narayana XA 事务不回滚问题定位问题背景用户反馈，在使用 ShardingSphere + Narayana 执行 XA 事务时，发生报错：java.sql.SQLException: javax.transaction.RollbackException: TransactionImple.enlistResource - ARJUNA016064: The transaction is in an invalid state!。这个报错的含义简单来说就是这个事务已经在其他地方被标记成只可回滚了，不能再进行后续其他的操作。报错信息如下： 12345678910111213141516171819202122Caused by: java.sql.SQLException: javax.transaction.RollbackException: TransactionImple.enlistResource - ARJUNA016064: The transaction is in an invalid state!        at...</div></div></div></a><a class="pagination-related" href="/articles/narayana/narayana01-init.html" title="Narayana 事务管理器初始化流程"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2023-12-06</div><div class="info-item-2">Narayana 事务管理器初始化流程</div></div><div class="info-2"><div class="info-item-1">事务管理器初始化流程总体流程12345678910创建 TransactionManagerImple    创建事务管理器对象读取 narayana 的 xml 配置，进行属性赋值获取 recovery 模块    加载恢复模块事务恢复日志的初始化初始化事务日志存储服务    JDBC方式存储        建表	文件方式存储  创建 TransactionManager 流程Narayana 会通过 BeanPopulator 反射创建对应的 TransactionManager 实例，并读取用户自定义的 xml 属性反射赋值到 TransactionManager 实例里。 1TransactionManager transactionManager =...</div></div></div></a><a class="pagination-related" href="/articles/narayana/narayana02-init-jdbc.html" title="Narayana启动-注册恢复模块流程"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2023-12-07</div><div class="info-item-2">Narayana启动-注册恢复模块流程</div></div><div class="info-2"><div class="info-item-1">Narayana启动-注册恢复模块流程使用代码12// narayana 在启动阶段使用如下 api 加载恢复模块XARecoveryModulexaRecoveryModule = XARecoveryModule.getRegisteredXARecoveryModule();  总体流程1234567891011121314151617注册恢复模块    反射创建 RecoveryEnvironmentBean 配置信息实例    加载 RecoveryActivators    启动 RecoveryActivators    初始化 PeriodicRecovery        设置恢复状态 INACTIVE        设置恢复mode ENABLED    加载恢复模块，module包括:    1.com.arjuna.ats.internal.arjuna.recovery.AtomicActionRecoveryModule   ...</div></div></div></a><a class="pagination-related" href="/articles/narayana/narayana03-begin.html" title="Narayana 事务 begin 流程"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2023-12-08</div><div class="info-item-2">Narayana 事务 begin 流程</div></div><div class="info-2"><div class="info-item-1">Narayana 事务 begin 流程整体流程12345检查事务状态获取超时时间创建事务对象    事务对象设置到 ThreadLocal 中,和当前线程绑定    插入事务测超时时间监控  使用 API123TransactionManager transactionManager = jtaPropertyManager.getJTAEnvironmentBean().getTransactionManager();// 开启全局事务transactionManager.begin();  调用链路123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869internal.jta.transaction.arjunacore.BaseTransaction#begin开启事务   ...</div></div></div></a><a class="pagination-related" href="/articles/narayana/narayana04-enlistResource.html" title="Narayana 事务资源注册流程"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2023-12-08</div><div class="info-item-2">Narayana 事务资源注册流程</div></div><div class="info-2"><div class="info-item-1">Narayana enlistResource流程XA 事务内每个物理连接执行第一条物理 sql 之前,需要执行 xa start 操作开启每个RM分支上的 xa 事务,并将 xaResource 注册到 TransactionManager 里。 整体流程12345678910transaction.enlistResource(xaResource)    执行 XA start xid        遍历 resource 判断当前是 isNewRM        创建 xid        createRecord        theTransaction.add(abstractRecord)            record 添加到 BasicAction.RecordList 里        执行 xa start 语句,若失败重试            MysqlXAConnection#start    把 XAResource 缓存到 map  使用1234567// 获取 XADataSourceXADataSource xaDatasource =...</div></div></div></a><a class="pagination-related" href="/articles/narayana/narayana05-commit.html" title="Narayana 事务 Commit 流程"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2023-12-11</div><div class="info-item-2">Narayana 事务 Commit 流程</div></div><div class="info-2"><div class="info-item-1">Narayana commit 流程整体流程123456789101112131415161718192021222324事务提交    判断是否能进行一阶段提交优化        若能一阶段提交            执行一阶段提交        否则            二阶段提交                prepare阶段                    执行 xa end                    执行 xa prepare                        xaResourceRecord 插入到 preparedList                            BasicAction#insertRecord                        更新状态 ActionStatus.COMMITTING                        保存状态，打包状态到 outputBuffer 里                            XAResourceRecord#save_state...</div></div></div></a></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info text-center"><div class="avatar-img"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info-name">flyingzc</div><div class="author-info-description">不积跬步无以至千里<br/>不积小流无以成江海</div><div class="site-data"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/FlyingZC"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons"><a class="social-icon" href="https://github.com/FlyingZC" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">FlyingZC's Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#ShardingSphere-XA%E4%BA%8B%E5%8A%A1%E6%97%A0%E6%B3%95%E6%81%A2%E5%A4%8D%E9%97%AE%E9%A2%98%E5%AE%9A%E4%BD%8D"><span class="toc-number">1.</span> <span class="toc-text">ShardingSphere-XA事务无法恢复问题定位</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%97%AE%E9%A2%98%E8%83%8C%E6%99%AF"><span class="toc-number">1.1.</span> <span class="toc-text">问题背景</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%97%AE%E9%A2%98%E5%AE%9A%E4%BD%8D"><span class="toc-number">1.2.</span> <span class="toc-text">问题定位</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9C%AC%E5%9C%B0%E6%90%AD%E5%BB%BA%E7%8E%AF%E5%A2%83%E5%B0%9D%E8%AF%95%E5%A4%8D%E7%8E%B0%E9%97%AE%E9%A2%98"><span class="toc-number">1.2.1.</span> <span class="toc-text">本地搭建环境尝试复现问题</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MySQL-%E6%8C%82%E6%8E%89%E5%90%8E%E4%BA%8B%E5%8A%A1%E6%81%A2%E5%A4%8D%E6%B5%81%E7%A8%8B"><span class="toc-number">1.2.2.</span> <span class="toc-text">MySQL 挂掉后事务恢复流程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%BE%BE%E6%A2%A6%E6%8C%82%E6%8E%89%E5%90%8E%E4%BA%8B%E5%8A%A1%E6%81%A2%E5%A4%8D%E6%B5%81%E7%A8%8B"><span class="toc-number">1.2.3.</span> <span class="toc-text">达梦挂掉后事务恢复流程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#XA%E8%A7%84%E8%8C%83"><span class="toc-number">1.2.4.</span> <span class="toc-text">XA规范</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%85%B6%E4%BB%96%E6%95%B0%E6%8D%AE%E5%BA%93%E5%A4%84%E7%90%86%E6%B5%81%E7%A8%8B"><span class="toc-number">1.2.5.</span> <span class="toc-text">其他数据库处理流程</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#postgresql-%E9%A9%B1%E5%8A%A8%E5%A4%84%E7%90%86-xa-%E5%BC%82%E5%B8%B8%E9%80%BB%E8%BE%91"><span class="toc-number">1.2.5.1.</span> <span class="toc-text">postgresql 驱动处理 xa 异常逻辑</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3"><span class="toc-number">1.3.</span> <span class="toc-text">问题解决</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%82%E8%80%83"><span class="toc-number">1.4.</span> <span class="toc-text">参考</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite03-transaction-begin.html" title="Apache Ignite 开启事务执行流程">Apache Ignite 开启事务执行流程</a><time datetime="2025-10-10T16:00:00.000Z" title="发表于 2025-10-11 00:00:00">2025-10-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite02-transaction.html" title="Apache Ignite 分布式事务原理">Apache Ignite 分布式事务原理</a><time datetime="2025-09-17T16:00:00.000Z" title="发表于 2025-09-18 00:00:00">2025-09-18</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite01-build.html" title="Apache Ignite IDEA 环境搭建">Apache Ignite IDEA 环境搭建</a><time datetime="2025-09-10T16:00:00.000Z" title="发表于 2025-09-11 00:00:00">2025-09-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/druid/druid01-resultset-leak.html" title="ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析">ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/jmeter/jmeter01-shardingsphere.html" title="Jmeter 压测 ShardingSphere">Jmeter 压测 ShardingSphere</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2025 By flyingzc</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="日间和夜间模式切换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>